package rpc

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"grpc/api-gateway/global"
	"grpc/common/etcd"
	"grpc/common/pb/user"
	"sync"
)

var (
	EtcdDiscovery *etcd.EtcdDiscovery
	discoverOnce  sync.Once
	UserClient    user.UserClient
)

func GetEtcdDiscover() (*etcd.EtcdDiscovery, error) {
	var err error = nil
	if EtcdDiscovery == nil {
		discoverOnce.Do(func() {
			endpoints := []string{global.Config.Etcd.Host + ":" + global.Config.Etcd.Port}
			EtcdDiscovery = &etcd.EtcdDiscovery{
				Address:    global.Config.Etcd.Host,
				Port:       global.Config.Etcd.Port,
				Endpoints:  endpoints,
				ServiceMap: make(map[string]string),
			}
			err = EtcdDiscovery.NewServiceDiscovery()
		})
	}
	return EtcdDiscovery, err
}

func InitClient() error {
	discovery, err := GetEtcdDiscover()
	if err != nil {
		return err
	}
	serviceNames := global.Config.System.ServiceNames
	for _, name := range serviceNames {
		err = discovery.ServiceDiscovery(name)
		if err != nil {
			return err
		}
		if name == "userService" {
			err = GetClient(name, discovery)
			if err != nil {
				return err
			}
			_, err := UserClient.UserRegister(context.Background(), &user.UserRegisterReq{})
			fmt.Println(err)
		}

	}
	return nil
}

func GetClient(serviceName string, etcdDiscovery *etcd.EtcdDiscovery) error {
	serviceAddr, err := etcdDiscovery.GetService(serviceName)
	conn, err := grpc.Dial(serviceAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}
	UserClient = user.NewUserClient(conn)
	return nil
}
